import {
  getAssessmentList,
  addAssessment,
  updateAssessment,
  updateAssessmentStatus,
  getAssessmentQuestions,
  addQuestions,
  deleteQuestions,
  updateQuestion
} from '@/api/assessment'

export default {
  data() {
    return {
      loading: false,
      questionLoading: false,
      assessmentList: [],
      questionList: [],
      total: 0,
      searchForm: {
        page: 1,
        pageSize: 10,
        category_id: '',
        keyWords: ''
      },
      assessmentDialogVisible: false,
      assessmentDialogTitle: '添加测评',
      assessmentForm: {
        id: null,
        name: '',
        category_id: '',
        introduction: '',
        coverImg: null,
        coverImgUrl: ''
      },
      assessmentRules: {
        name: [{ required: true, message: '请输入测评名称', trigger: 'blur' }],
        category_id: [{ required: true, message: '请选择分类', trigger: 'change' }],
        introduction: [{ required: true, message: '请输入测评介绍', trigger: 'blur' }]
      },
      questionDialogVisible: false,
      questionFormVisible: false,
      questionDialogTitle: '添加题目',
      currentAssessment: {},
      questionForm: {
        id: null,
        topic: '',
        question_type: 'choice',
        options: ['', ''],
        sort_order: 0
      },
      questionRules: {
        topic: [{ required: true, message: '请输入题目内容', trigger: 'blur' }],
        question_type: [{ required: true, message: '请选择题型', trigger: 'change' }]
      }
    }
  },
  computed: {
    showOptions() {
      return ['choice', 'judge'].includes(this.questionForm.question_type)
    }
  },
  mounted() {
    this.getAssessmentList()
  },
  methods: {
    applyLocalReorder(assessmentId, questionId, targetOrder) {
      // const key = `assessment_sort_${assessmentId}`
      const current = [...this.questionList]
      current.sort((a, b) => (a.displayOrder ?? a.sortOrder ?? 0) - (b.displayOrder ?? b.sortOrder ?? 0))
      const idx = current.findIndex(q => q.questionId === questionId)
      if (idx < 0) return
      const [item] = current.splice(idx, 1)
      const k = Math.max(1, Math.min(targetOrder, current.length + 1))
      current.splice(k - 1, 0, item)
      this.questionList = this.normalizeAndPersistOrders(assessmentId, current)
    },

    normalizeAndPersistOrders(assessmentId, list) {
      const ordered = [...list].sort((a, b) => {
        const aKey = (a.displayOrder && a.displayOrder > 0) ? a.displayOrder : ((a.sortOrder && a.sortOrder > 0) ? a.sortOrder : Infinity)
        const bKey = (b.displayOrder && b.displayOrder > 0) ? b.displayOrder : ((b.sortOrder && b.sortOrder > 0) ? b.sortOrder : Infinity)
        if (aKey !== bKey) return aKey - bKey
        return (a.questionId || 0) - (b.questionId || 0)
      })
      const orderMap = {}
      ordered.forEach((q, i) => {
        q.displayOrder = i + 1
        orderMap[q.questionId] = q.displayOrder
      })
      localStorage.setItem(`assessment_sort_${assessmentId}`, JSON.stringify(orderMap))
      return ordered
    },

    isValidImageUrl(url) {
      if (!url) return false
      return /^https?:\/\//i.test(url)
    },

    getCoverUrl(row) {
      const placeholder = ''
      const url = row && row.coverImgUrl
      if (this.isValidImageUrl(url)) return url
      return placeholder
    },

    onCoverError(row) {
      const placeholder = ''
      if (row) {
        row.coverImgUrl = placeholder
        try {
          const key = 'assessment_cover_map'
          const map = JSON.parse(localStorage.getItem(key) || '{}')
          map[row.id] = placeholder
          localStorage.setItem(key, JSON.stringify(map))
        } catch (e) {
          console.warn('保存封面映射失败:', e)
        }
      }
    },

    handleImageError(e) {
      console.warn('图片加载失败:', e.target.src)
    },

    async getAssessmentList() {
      this.loading = true
      try {
        const result = await getAssessmentList(this.searchForm)
        if (result && result.code === 1) {
          const data = result.data || {}
          const records = data.records || data.list || []
          const coverCacheKey = 'assessment_cover_map'
          const coverMap = JSON.parse(localStorage.getItem(coverCacheKey) || '{}')

          this.assessmentList = Array.isArray(records) ? records.map(item => {
            const processedItem = { ...item }
            if (item.coverImg && !item.coverImgUrl) {
              processedItem.coverImgUrl = item.coverImg
            }
            if (item.coverImgUrl && !item.coverImg) {
              processedItem.coverImg = item.coverImgUrl
            }
            if ((!processedItem.coverImgUrl || processedItem.coverImgUrl === '') && coverMap[item.id]) {
              processedItem.coverImgUrl = coverMap[item.id]
              processedItem.coverImg = coverMap[item.id]
            }
            if (processedItem.coverImgUrl) {
              const url = processedItem.coverImgUrl
              const looksLikeHttp = /^https?:\/\//i.test(url)
              if (!looksLikeHttp) {
                processedItem.coverImgUrl = ''
                processedItem.coverImg = ''
              }
            }
            if (!processedItem.questionsCount) {
              if (processedItem.questionCount) {
                processedItem.questionsCount = processedItem.questionCount
              } else if (processedItem.count) {
                processedItem.questionsCount = processedItem.count
              } else {
                processedItem.questionsCount = 0
              }
            }
            return processedItem
          }) : []

          const newCoverMap = { ...coverMap }
          this.assessmentList.forEach(it => {
            if (it.coverImgUrl) newCoverMap[it.id] = it.coverImgUrl
          })
          localStorage.setItem(coverCacheKey, JSON.stringify(newCoverMap))

          if (this.assessmentList.length > 0) {
            for (const assessment of this.assessmentList) {
              try {
                const questionResult = await getAssessmentQuestions({ assessment_id: assessment.id })
                if (questionResult && questionResult.code === 1) {
                  const questionCount = Array.isArray(questionResult.data) ? questionResult.data.length : 0
                  assessment.questionsCount = questionCount
                }
              } catch (error) {
                assessment.questionsCount = 0
              }
            }
          }

          const rawTotal = data.total ?? data.count ?? 0
          this.total = (typeof rawTotal === 'number' && rawTotal > 0)
            ? rawTotal
            : (Array.isArray(this.assessmentList) ? this.assessmentList.length : 0)
        } else {
          this.$message && this.$message.error(`获取测评列表失败: ${result?.msg || '未知错误'}`)
        }
      } catch (error) {
        this.$message && this.$message.error(`获取测评列表异常: ${error.message}`)
      } finally {
        this.loading = false
      }
    },

    handleSearch() {
      this.searchForm.page = 1
      this.getAssessmentList()
    },

    handleReset() {
      this.searchForm = {
        page: 1,
        pageSize: 10,
        category_id: '',
        keyWords: ''
      }
      this.getAssessmentList()
    },

    handleSizeChange(val) {
      this.searchForm.pageSize = val
      this.getAssessmentList()
    },

    handleCurrentChange(val) {
      this.searchForm.page = val
      this.getAssessmentList()
    },

    showAddAssessmentDialog() {
      this.assessmentDialogTitle = '添加测评'
      this.assessmentForm = {
        id: null,
        name: '',
        category_id: '',
        introduction: '',
        coverImg: null,
        coverImgUrl: ''
      }
      this.assessmentDialogVisible = true
      this.$nextTick(() => {
        this.$refs.assessmentForm && this.$refs.assessmentForm.clearValidate()
      })
    },

    editAssessment(row) {
      this.assessmentDialogTitle = '编辑测评'
      this.assessmentForm = {
        id: row.id,
        name: row.name,
        category_id: row.categoryId,
        introduction: row.introduction,
        coverImg: null,
        coverImgUrl: row.coverImgUrl
      }
      this.assessmentDialogVisible = true
    },

    saveAssessment() {
      this.$refs.assessmentForm.validate(async valid => {
        if (valid) {
          try {
            if (this.assessmentForm.id) {
              const formData = new FormData()
              formData.append('assessment_id', this.assessmentForm.id.toString())
              formData.append('name', this.assessmentForm.name)
              formData.append('category_id', this.assessmentForm.category_id)
              formData.append('introduction', this.assessmentForm.introduction)

              if (this.assessmentForm.coverImg) {
                // 新上传图片，传文件
                formData.append('coverImg', this.assessmentForm.coverImg)
              } else {
                // 兼容部分后端“字段必传”校验：传递空文件占位
                const emptyBlob = new Blob([''], { type: 'application/octet-stream' })
                formData.append('coverImg', emptyBlob, 'empty.txt')
              }
              // 不再附带 coverImgUrl，避免后端 400

              await updateAssessment(formData)
              this.$message.success('测评更新成功')
              try {
                const coverCacheKey = 'assessment_cover_map'
                const coverMap = JSON.parse(localStorage.getItem(coverCacheKey) || '{}')
                if (this.assessmentForm.coverImgUrl) {
                  coverMap[this.assessmentForm.id] = this.assessmentForm.coverImgUrl
                }
                localStorage.setItem(coverCacheKey, JSON.stringify(coverMap))
              } catch (e) {
                console.warn('保存封面缓存失败:', e)
              }
            } else {
              const formData = new FormData()
              formData.append('name', this.assessmentForm.name)
              formData.append('category_id', this.assessmentForm.category_id)
              formData.append('introduction', this.assessmentForm.introduction)
              if (this.assessmentForm.coverImg) {
                formData.append('coverImg', this.assessmentForm.coverImg)
              }
              await addAssessment(formData)
              this.$message.success('测评添加成功')
            }

            this.assessmentDialogVisible = false
            this.getAssessmentList()
          } catch (error) {
            this.$message.error(`保存失败: ${error.message}`)
          }
        }
      })
    },

    handleCoverUpload(options) {
      this.assessmentForm.coverImg = options.file
      this.assessmentForm.coverImgUrl = URL.createObjectURL(options.file)
    },

    async toggleStatus(row) {
      try {
        const newStatus = row.status === 1 ? 2 : 1
        await updateAssessmentStatus({
          assessment_id: row.id,
          status: newStatus
        })
        this.$message.success('状态更新成功')
        this.getAssessmentList()
      } catch (error) {
        console.error('更新状态失败:', error)
      }
    },

    async viewQuestions(row) {
      this.currentAssessment = row
      this.questionDialogVisible = true
      await this.getQuestionList(row.id)
    },

    async getQuestionList(assessmentId) {
      this.questionLoading = true
      try {
        const result = await getAssessmentQuestions({ assessment_id: assessmentId })
        if (result && result.code === 1) {
          const normalizeOptions = (opts) => {
            if (Array.isArray(opts)) return opts
            if (typeof opts === 'string') {
              const text = opts.trim()
              if (!text) return []
              try {
                return JSON.parse(text)
              } catch (e) {
                const inner = text.replace(/^\[|\]$/g, '')
                if (!inner.trim()) return []
                return inner.split(',').map(s => s.replace(/^\s*"?|"?\s*$/g, '').trim()).filter(Boolean)
              }
            }
            return []
          }

          let list = result.data.map(item => ({
            questionId: item.questionId ?? item.id,
            assessmentId: item.assessmentId ?? item.assessment_id,
            topic: item.topic,
            questionType: item.questionType ?? item.question_type,
            options: normalizeOptions(item.options),
            sortOrder: item.sortOrder ?? item.sort_order ?? 0
          }))

          const key = `assessment_sort_${assessmentId}`
          const saved = localStorage.getItem(key)
          if (saved) {
            try {
              const orderMap = JSON.parse(saved)
              list = list.map((q, idx) => {
                const savedOrder = orderMap[q.questionId]
                const fallbackOrder = (q.sortOrder && q.sortOrder > 0) ? q.sortOrder : (idx + 1)
                return {
                  ...q,
                  displayOrder: (typeof savedOrder === 'number' && savedOrder > 0) ? savedOrder : fallbackOrder
                }
              })
              list.sort((a, b) => (a.displayOrder || 0) - (b.displayOrder || 0))
            } catch (e) {
              console.warn('恢复题目顺序失败:', e)
            }
          } else {
            list = list.map((q, idx) => ({ ...q, displayOrder: (q.sortOrder && q.sortOrder > 0) ? q.sortOrder : (idx + 1) }))
          }

          this.questionList = this.normalizeAndPersistOrders(assessmentId, list)
        }
      } catch (error) {
        console.error('获取题目列表失败:', error)
      } finally {
        this.questionLoading = false
      }
    },

    showAddQuestionDialog() {
      this.questionDialogTitle = '添加题目'
      this.questionForm = {
        id: null,
        topic: '',
        question_type: 'choice',
        options: ['', ''],
        sort_order: this.questionList.length
      }
      this.questionFormVisible = true
      this.$nextTick(() => {
        this.$refs.questionForm && this.$refs.questionForm.clearValidate()
      })
    },

    showEditQuestionDialog(row) {
      this.questionDialogTitle = '编辑题目'
      this.questionForm = {
        id: row.questionId,
        topic: row.topic,
        question_type: row.questionType,
        options: [...row.options],
        sort_order: row.sortOrder
      }
      this.questionFormVisible = true
    },

    saveQuestion() {
      this.$refs.questionForm.validate(async valid => {
        if (valid) {
          try {
            const questionData = {
              topic: this.questionForm.topic,
              question_type: this.questionForm.question_type,
              options: this.questionForm.options,
              sort_order: this.questionForm.sort_order
            }

            if (this.questionForm.id) {
              const updateData = {
                ...questionData,
                question_id: this.questionForm.id,
                assessment_id: this.currentAssessment && this.currentAssessment.id
              }
              await updateQuestion(updateData)
              this.$message.success('题目更新成功')
            } else {
              const questions = [{
                assessment_id: this.currentAssessment.id,
                topic: questionData.topic,
                question_type: questionData.question_type,
                options: questionData.options,
                sort_order: questionData.sort_order
              }]
              await addQuestions(questions)
              this.$message.success('题目添加成功')
            }
            this.questionFormVisible = false

            await this.getQuestionList(this.currentAssessment.id)
            let targetId
            if (this.questionForm.id) {
              targetId = this.questionForm.id
            } else {
              const latest = this.questionList.reduce((a, b) => (a.questionId > b.questionId ? a : b), this.questionList[0])
              targetId = latest ? latest.questionId : null
            }
            if (targetId) {
              this.applyLocalReorder(this.currentAssessment.id, targetId, Number(this.questionForm.sort_order) || 1)
            }

            await this.getAssessmentList()
          } catch (error) {
            console.error('保存题目失败:', error)
          }
        }
      })
    },

    handleTypeChange(type) {
      if (type === 'judge') {
        this.questionForm.options = ['是', '否']
      } else if (type === 'choice') {
        this.questionForm.options = ['', '']
      } else {
        this.questionForm.options = []
      }
    },

    addOption() {
      this.questionForm.options.push('')
    },

    removeOption(index) {
      if (this.questionForm.options.length > 2) {
        this.questionForm.options.splice(index, 1)
      } else {
        this.$message.warning('至少需要两个选项')
      }
    },

    handleDeleteQuestion(row) {
      this.$confirm('确定删除该题目吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        try {
          await deleteQuestions([row.questionId])
          this.$message.success('删除成功')
          await this.getQuestionList(this.currentAssessment.id)
          await this.getAssessmentList()
        } catch (error) {
          console.error('删除题目失败:', error)
        }
      }).catch(() => {})
    }
  }
}

